<?php
namespace ServiceBundle\Model;

use RedUnicorn\SymfonyKernel\Appoint\Model\BuiltInDataInterface;
use RedUnicorn\SymfonyKernel\Model\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use RedUnicorn\Validate\Validate;
use ServiceBundle\Entity\Area;

class m_area extends Model implements BuiltInDataInterface
{

    /**
     * @var Area
     */
    private $area_class = null;

    function __construct(ContainerInterface $container)
    {   

        parent::__construct($container, 'area');
    }
 
    public function validate($data, $id = false)
    {
        $this->entityManager = $this->getDoctrine()->getManager();
        
        if(empty($id)){
            $this->area_class = new Area();
        }else{
            if(!$this->is_exist($id)){
                self::$error->setError($this->get('translator')->trans('未找到对应信息'));
                return false;
            }

            $this->area_class = $this->entityManager->getRepository(Area::class)->find($id);
        }
                        
        if(array_key_exists('parent_id', $data)){
            if($data['parent_id'] !== null) {
                $this->area_class->setParent($this->entityManager->getRepository(\ServiceBundle\Entity\Area::class)->find($data['parent_id']));
                if(empty($this->area_class->getParent())){
                    self::$error->setError($this->get('translator')->trans('parent_id:' . $data['parent_id'] . ' 未找到'));
                    return false;
                }
            }else{
                $this->area_class->setParent(null);
            }
        }
         
        if(self::$error->validate($this->area_class)){
            return false;
        }
        
        return true;
    }
    
    public function insert($data)
    {
        if(!$this->validate($data)){
            return false;
        }
        
        
        $this->entityManager->persist($this->area_class);
        $this->entityManager->flush();
    
        $this->lastInsertId = $this->area_class->getId();

        return true;
    }
    
    public function update($id ,$data)
    {
        if(empty($id)){
            self::$error->setError('param id is not null');
            return false;
        }
        
        if(!$this->validate($data, $id)){
            return false;
        }
        
        $this->entityManager->flush();

        return true;
    }
    
    public function rewritesRule(&$rule)
    {   
                    
        //TODO where   
        if(array_key_exists('id', $rule) && !Validate::isRealEmpty($rule['id'])){
            $this->sql_array['where'] .= " AND sql_pre.id LIKE '{$rule['id']}' ";
        }
                    
        //TODO where   
        if(array_key_exists('parent_id', $rule)){
           $this->sql_array['where'] .= " AND sql_pre.parent_id = '{$rule['parent_id']}' ";
        }
                    
        //TODO where   
        if(array_key_exists('name', $rule) && !Validate::isRealEmpty($rule['name'])){
            $this->sql_array['where'] .= " AND sql_pre.name LIKE '{$rule['name']}' ";
        }
                    
        //TODO where   
        if(array_key_exists('first_letter', $rule) && !Validate::isRealEmpty($rule['first_letter'])){
            $this->sql_array['where'] .= " AND sql_pre.first_letter LIKE '{$rule['first_letter']}' ";
        }

        //TODO where 城市
        if(array_key_exists('where_city', $rule)){
            $this->sql_array['where'] .= ' AND sql_pre.parent_id IN (SELECT id FROM area WHERE parent_id = 0 AND id != 0)';
        }

        $this->sql_array['where'] .= ' AND sql_pre.id <> 0';
        $this->sql_array['order_by'] = ' sql_pre.name ASC ,';
    }

    /**
     * 根据ID得到下辖省市区信息
     *
     * @param int $area_id
     * @return mixed
     */
    public function getSubordination($area_id = 0)
    {
        return $this->getAllList([
            'parent_id' => $area_id
        ]);
    }

    /**
     * 联表查询省市区信息SQL拼接
     *
     * @param $select
     * @param $join
     * @param string $pre
     */
    public static function leftJoinTcn(&$select, &$join, $pre = '')
    {
        if(strpos($select, 'province_id') !== false){
            $select .= ", area_p.name as province_name ";
            $join .= " LEFT JOIN area area_p on area_p.id = {$pre}province_id ";
        }

        if(strpos($select, 'city_id') !== false){
            $select .= ", area_c.name as city_name ";
            $join .= " LEFT JOIN area area_c on area_c.id = {$pre}city_id ";
        }

        if(strpos($select, 'district_id') !== false){
            $select .= ", area_d.name as district_name ";
            $join .= " LEFT JOIN area area_d on area_d.id = {$pre}district_id ";
        }
    }

    /**
     * 得到地址名称
     *
     * @param $area_id
     * @return mixed
     */
    public function getAreaName($area_id)
    {
        return $this->getColumn('sql_pre.name', array('id' => $area_id));
    }

    /**
     * 得到全部的城市
     *
     * request.sort  是否按首字母分组归纳 def(0)
     * request.name  名称搜索关键词
     *
     * @return array
     */
    public function getAllCity()
    {
        $sort = self::$request->get('sort');

        $citiesFromDb = $this->getAllList([
            'where_city' => 1,
            'name' => self::$request->get('name')
        ]);

        $cities = array();

        if($sort == 1){
            foreach ($citiesFromDb as $value) {
                if(!empty($value['first_letter'])) {
                    $cities[$value['first_letter']][] = array(
                        'id' => $value['id'],
                        'name' => $value['name']
                    );
                }
            }
            ksort($cities);
        }else{
            $cities = $citiesFromDb;
        }

        return $cities;
    }

    /**
     * 得到全部的省市区
     *
     * request.is_hierarchy 是否层级化 | def(0)
     *
     * @return mixed
     */
    public function getAll()
    {
        $area = $this->getAllList();

        if(self::$request->get('is_hierarchy') == 1) {
            $areas = $this->findChildren($area, 'id', 'parent_id');

            return $areas;
        }

        return $area;
    }

    /**
     * 根据城市名得到城市id
     *
     * @param $city_name
     * @return bool|mixed
     */
    public function getCityId($city_name)
    {
        $city_name = rtrim($city_name, '市');

        if(empty($city_name)){
            return false;
        }

        return $this->getId(['name' => $city_name, 'where_city' => 1]);
    }


    public function builtInData()
    {
        // TODO: Implement builtInData() method.
        $data = $this->get('unicorn.files')->readToJson(__DIR__ . '/../Resources/Data/area.json');

        foreach ($data as $area){
            self::$conn->insert($this->table_name, $area);
        }
    }


    /**
     * 数据层级化
     *
     * @param array $arr
     * @param string $id
     * @param string $pid
     * @return mixed
     */
    private function findChildren(array $arr, $id = 'id', $pid = 'parent_id')
    {
        $data = [];
        foreach($arr as $v) $data[$v[$id]] = $v;
        foreach ($data as $k => $item){
            if( $item[$pid]) {
                $data[$item[$pid]]['child'][$item[$id]] = & $data[$k];
            }
        }

        foreach ($data as $key=>$value) {
            if ($value['parent_id']) {
                unset($data[$key]);
            }
        }

        return $this->fixKeys($data);
    }

    /**
     * 整理key
     *
     * 功能实现策略：如果数组key中存在一个数字就将该数组中的全部value取出变为新的数组
     *
     * @param $array
     * @return array
     */
    private function fixKeys($array)
    {
        $numberCheck = false;
        foreach ($array as $k => $val) {
            if (is_array($val)) {
                $array[$k] = $this->fixKeys($val); //递归
                if (is_numeric($k)) $numberCheck = TRUE;
            }
        }

        if ($numberCheck === true) {
            return array_values($array);
        } else {
            return $array;
        }
    }
}